package com.houdoudou.customer.me;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Customer;
import com.houdoudou.customer.CustomerMainActivity;
import com.houdoudou.customer.FrgBuyOfActMain;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.TransPasswordUtil;
import com.houdoudou.customer.common.UniversalHttpPost;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class RegistAct extends Activity{

	ImageButton back;
	Button regist,getverify;
	EditText tel,secret1,secret2,verify;
	ProgressBar progres;
	TextView  result;
	View.OnClickListener myOnClickListener;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_regist);
		init_listener();
		
		regist=(Button) findViewById(R.id.btn_regist_act_regist);
		tel= (EditText) findViewById(R.id.et_tel_act_regist);
		secret1=(EditText) findViewById(R.id.et_secret1_act_regist);
		secret2=(EditText) findViewById(R.id.et_secret2_act_regist);
		back=(ImageButton) findViewById(R.id.back_act_regist);
		progres= (ProgressBar) findViewById(R.id.prgs_act_regist);
		result= (TextView) findViewById(R.id.tv_result_act_regist);
		verify= (EditText) findViewById(R.id.et_verifycode_act_regist);
		getverify=(Button) findViewById(R.id.btn_getverifycode_act_regist);
		
		progres.setVisibility(View.GONE);
		result.setVisibility(View.GONE);
		
		back.setOnClickListener(myOnClickListener);
		getverify.setOnClickListener(myOnClickListener);
		regist.setOnClickListener(myOnClickListener);
		
	}

	private void init_listener(){
		myOnClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(v==back){
					new Thread () { 
						public void run () { 
						try { 									
						Instrumentation inst= new Instrumentation(); 
						inst.sendKeyDownUpSync(KeyEvent. KEYCODE_BACK); 
						} catch(Exception e) { 
						e.printStackTrace(); 
						         } 
						  } 
						}.start();
				 }
				if(v==getverify){
					    getverify.setClickable(false);
					    progres.setVisibility(View.VISIBLE);					
						result.setVisibility(View.GONE);
						String[] params= new String[5];
			            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
		                params[1]="createTelnumVerify"; //PostCod
		                JSONObject jsonData=new JSONObject();								
			            jsonData.put("telnum", tel.getText().toString());		               
			            params[2]=jsonData.toString();
		             new HttpPostTaskforGetVerify().execute(params);
				}
				if(v==regist){
					boolean checkinput=true;
					if(tel.getText().toString().length()!=11){
						checkinput=false;
						Toast.makeText(RegistAct.this, "电话号码位数不对",Toast.LENGTH_SHORT ).show();}
					if(!secret1.getText().toString().equals(secret2.getText().toString())){
						checkinput=false;
						Toast.makeText(RegistAct.this, "两次密码输入不一致",Toast.LENGTH_SHORT ).show();}
					if(verify.getText().toString().length()!=4){
						checkinput=false;
						Toast.makeText(RegistAct.this, "验证码位数不对",Toast.LENGTH_SHORT ).show();}
					if(secret1.getText().toString().length()>20){
						checkinput=false;
						Toast.makeText(RegistAct.this, "密码长度不可超过20位",Toast.LENGTH_SHORT ).show();}
					if(checkinput){
					  progres.setVisibility(View.VISIBLE);					
						result.setVisibility(View.GONE);
						 getverify.setClickable(false);
						 regist.setClickable(false);
						String[] params= new String[5];
			            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
		                params[1]="createCustomer"; //PostCod
		                JSONObject jsonData=new JSONObject();	
		                
						 JSONObject jsonVerify= new JSONObject();
						 jsonVerify.put("telnum",  tel.getText().toString());
						 jsonVerify.put("code", verify.getText().toString());
						 jsonData.put("verify", jsonVerify);
						 
						 JSONObject jsonCustomer= new JSONObject();
						 try {
							String cipherText= TransPasswordUtil.encrypt(secret1.getText().toString());
							 jsonCustomer.put(Customer.SECRET, cipherText);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			             jsonCustomer.put(Customer.TELNUM, tel.getText().toString());			               
			            
			             jsonCustomer.put(Customer.SPARETELNUM, tel.getText().toString());	
			              
			               jsonData.put("customer", jsonCustomer);  
			               
			                params[2]=jsonData.toString();
		             new HttpPostTaskforRegist().execute(params);
					}
				}
				
				
			}
		};
	}
	
	
private  class HttpPostTaskforGetVerify extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
		
			 progres.setVisibility(View.GONE);	
			 getverify.setClickable(true);
			
			 System.out.println("-----------onPostExecute()--------------");
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 result.setVisibility(View.VISIBLE);
				  result.setText("无法连接服务器,");
		      
			}else{
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean success=false;
				String errorInfo="";
				JSONObject json = null;
				try{
			     json= JSONObject.fromObject(PostResult);
				 success=json.getBoolean("success");
				 errorInfo=json.getString("errorInfo");	
				}catch(JSONException e){
					 result.setVisibility(View.VISIBLE);
					  result.setText("数据解析错误");
				}
										   												      		       
		       if(success){     
		    	  	getverify.setText("验证码已发送");		               	  	    	 
		             }else{
		            	 result.setVisibility(View.VISIBLE);
		            	 result.setText(errorInfo); 
		             } 			
		  		         
				  }// if 网络正常结束
			
		} //onPostExecute
 } //AsyncTask
	

private  class HttpPostTaskforRegist extends android.os.AsyncTask<String,String,Map<String,Object>>{

	

	@Override
	protected Map<String,Object> doInBackground(String... params) {
		// TODO Auto-generated method stub
		 Map<String,Object> map = new HashMap<String ,Object>();		
	  map =	UniversalHttpPost.doPost(params);	             
		return map;
	}
	
	@Override
	protected void onPostExecute(Map<String,Object> map) {
	
		 progres.setVisibility(View.GONE);	
		 getverify.setClickable(true);
		 regist.setClickable(true);
		 System.out.println("-----------onPostExecute()--------------");
		 String PostResult=(String) map.get("PostResult");		 
		 boolean networkstate=(Boolean) map.get("PostState");
		 if(!networkstate){
			 result.setVisibility(View.VISIBLE);
			  result.setText("无法连接服务器,");
	      
		}else{
		//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
			Boolean success=false;
			String errorInfo="";
			JSONObject json = null;
			try{
		     json= JSONObject.fromObject(PostResult);
			 success=json.getBoolean("success");
			 errorInfo=json.getString("errorInfo");	
			}catch(JSONException e){
				 result.setVisibility(View.VISIBLE);
				  result.setText("数据解析错误");
			}
									   												      		       
	       if(success){     
	    	  			               	  
				  	 		    	   
	    	   Builder b = new AlertDialog.Builder(RegistAct.this).setTitle("注册成功")  
					     .setMessage("是否登录？");  
					   b.setPositiveButton("登录", new DialogInterface.OnClickListener() {  
					    public void onClick(DialogInterface dialog, int whichButton) {  
					    	
					    	Intent mIntent = new Intent(RegistAct.this,LoginAct.class); 
					    	RegistAct.this.startActivity(mIntent);   
					    }  
					   })
					   .setNegativeButton("取消",new DialogInterface.OnClickListener() {  
						    public void onClick(DialogInterface dialog, int whichButton) {  
							     dialog.cancel();  
							   
							    }  
					   }).show();  
	             }else{
	            	 result.setVisibility(View.VISIBLE);
	            	 result.setText(errorInfo); 
	             } 			
	  		         
			  }// if 网络正常结束
		
	} //onPostExecute
} //AsyncTask
}
